#include <stdio.h>
#include "flash.h"
#include "upgrade.h"


int ClearUpgradeFlag(void)
{
    uint32_t thisBoardUpgradeFlag=0xAAAAAAAA;

    flash_read_word(UPGRADE_FLAG_ADDR,&thisBoardUpgradeFlag,1);
    if(thisBoardUpgradeFlag != 0xFFFFFFFF)
    {
        fmc_unlock();
        /* Clear All pending flags */
        // fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_WPERR|FMC_FLAG_PGAERR|FMC_FLAG_PGERR);

        //broken event flag
        uint32_t tmp = *(uint32_t*)(UPGRADE_FLAG_ADDR+4);

        fmc_page_erase(UPGRADE_FLAG_ADDR);

        fmc_word_program(UPGRADE_FLAG_ADDR+4,tmp);
    //    fmc_word_program(UPGRADE_FLAG_ADDR,thisBoardUpgradeFlag);
        // fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_WPERR|FMC_FLAG_PGAERR|FMC_FLAG_PGERR);
        fmc_lock();

        flash_read_word(UPGRADE_FLAG_ADDR,&thisBoardUpgradeFlag,1);
        if(thisBoardUpgradeFlag != 0xFFFFFFFF)
        {
            printf("upgrade flag clear fail,readback value is:0x%08X\r\n",thisBoardUpgradeFlag);
            return -1;
        }
    }

    // printf("upgrade flag clear success\r\n");

    return 0;
}

// int SimulateUpgrade(void)
// {
//     uint32_t thisBoardUpgradeFlag=UPGRADE_AVAILABLE_FLAG;

//     uint32_t temp = *(uint32_t*)(UPGRADE_FLAG_ADDR+4);

//     fmc_unlock();
//     fmc_page_erase(UPGRADE_FLAG_ADDR);
//     fmc_word_program(UPGRADE_FLAG_ADDR,thisBoardUpgradeFlag);
//     fmc_word_program(UPGRADE_FLAG_ADDR+4,temp);
//     fmc_lock();

//     flash_read_word(UPGRADE_FLAG_ADDR,&thisBoardUpgradeFlag,1);
//     if(thisBoardUpgradeFlag != UPGRADE_AVAILABLE_FLAG)
//     {
//         printf("upgrade flag write fail,readback value is:0x%08X\r\n",thisBoardUpgradeFlag);
//         return -1;
//     }

//     // printf("upgrade flag clear success\r\n");

//     return 0;
// }

#if 0
int SetUpgradeFlag(void)
{
    uint32_t thisBoardUpgradeFlag=0xAAAAAAAA;

    fmc_unlock();
    /* Clear All pending flags */
    fmc_flag_clear(FMC_FLAG_BANK0_END | FMC_FLAG_BANK0_WPERR | FMC_FLAG_BANK0_PGERR);

    fmc_page_erase(UPGRADE_FLAG_ADDR);
    fmc_word_program(UPGRADE_FLAG_ADDR,thisBoardUpgradeFlag);
    fmc_flag_clear(FMC_FLAG_BANK0_END | FMC_FLAG_BANK0_WPERR | FMC_FLAG_BANK0_PGERR);
    fmc_lock();

    flash_read_word(UPGRADE_FLAG_ADDR,&thisBoardUpgradeFlag,1);
    if(thisBoardUpgradeFlag != 0xAAAAAAAA)
    {
        printf("upgrade flag set fail,readback value is:0x%08X\r\n",thisBoardUpgradeFlag);
        return -1;
    }


    // printf("upgrade flag set success\r\n");

    return 0;
}
#endif



